package gat.common.util;

import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 设置消息内容
 *
 * @return template
 */
public class MessageReplaceUtil {
    /**
     * 进行短信的拼接
     * @param template
     * @param params
     * @return
     */
    public static String replace(String template, Map<String,String> params) {

        /*for (MessageParamReqVo.Params param : params.getParamsList()) {
            //需要被替换的内容
            String temp = "\\$\\{" + param.getParamCode() + "\\}";
            //设置匹配参数
            Pattern pattern = Pattern.compile(temp);
            Matcher matcher = pattern.matcher(template);
            //进行替换
            template = matcher.replaceAll(param.getParamDesc());
        }*/
        if (MapUtil.isEmpty(params)) {
            return template;
        }
        for (Map.Entry<String, String> entry : params.entrySet()) {
            //需要被替换的内容
            String param = "\\$\\{" + entry.getKey() + "\\}";

            //设置匹配参数
            Pattern pattern = Pattern.compile(param);
            Matcher matcher = pattern.matcher(template);
            if (StrUtil.isBlank(entry.getValue())){
                entry.setValue(" ");
            }
            //进行替换
            template = matcher.replaceAll(entry.getValue());
        }

        return template;

    }

    /**
     * 获取模板内的参数
     * @param template
     * @return
     */
    public static List<String>  getParams(String template) {
        // 获取参数信息
        List<String> list = new ArrayList<>();
        //匹配大括号
        String regex = "\\$\\{([^}]*)\\}";
        //匹配小括号
        Pattern pattern = Pattern.compile(regex);
        Matcher matcher = pattern.matcher(template);
        while (matcher.find()){
            list.add(matcher.group());
        }
        List newList = list.stream().distinct().collect(Collectors.toList());
        return newList;
    }

    public static void main(String[] args) {
        String template = "尊敬的${name}：${username}提交了线下充值申请${offlinePayNo}，请前往${url}进行查看审核。" ;
        Map<String,String> params = new HashMap<>();
        params.put("name", "1q");
        params.put("username","222");
        System.out.println(replace(template,params));
    }
}
